<style lang="scss">
.pcomputed {

    @mixin n-row1 {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    &,
    *:not([class^='el-']) {
        margin: 0;
        padding: 0;
        font: inherit;
        color: inherit;
        list-style: none;
        outline: none;
        box-sizing: border-box;
    }

    width: 100%;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;
    position: relative;
    padding: 20px !important;

    .pcomputed-list {
        background: #fff;

        >li {
            padding: 20px;
            border-bottom: 1px solid #eee;

            >h3 {
                color: #000;
                font-weight: bold;
                @include n-row1;
                font-size: 16px;
            }

            .pcomputed-list-des {
                @include n-row1;
                margin-top: 40px;
                font-size: 14px;
                color: #555;
                gap: 20px;
                align-items: flex-start;

                >span {
                    @include n-row1;
                    justify-content: flex-end;
                    height: 30px;
                }

                >div {
                    flex: 1;
                    width: 0;

                    >p {
                        @include n-row1;
                        gap: 10px;
                        justify-content: flex-start;
                        margin-bottom: 15px;

                        .el-input {
                            width: 200px;
                        }
                    }
                }
            }

            >p {
                color: #999;
                font-size: 13px;
                @include n-row1;
                margin-top: 20px;
                background: #f6f6f6;
                padding: 10px;
                gap: 10px;

                >img {
                    width: 200px;
                }
            }

            >footer {
                margin-top: 20px;
                @include n-row1;

                >span {
                    color: #999;
                    font-size: 14px;
                    flex: 1;
                    width: 0;
                    font-style: initial;
                }
            }
        }
    }

    .pcomputed-res {
        margin-top: 20px;
        background: #fff;
        padding: 20px;

        >h3 {
            @include n-row1;
            justify-content: center;
            font-weight: bold;
            color: #000;
            font-size: 24px;
            line-height: 50px;
        }

        >h4 {
            @include n-row1;
            justify-content: flex-start;
            font-weight: bold;
            color: #000;
            font-size: 20px;
            line-height: 50px;
            margin-top: 20px;
        }

        >ul {
            @include n-row1;
            margin-top: 10px;
            flex-wrap: wrap;
            font-size: 18px;
            align-content: flex-start;

            >li {
                height: 36px;
                border-bottom: 1px solid #eee;
                flex: 0 0 50%;
                width: 0;
                padding: 0 10px;
                @include n-row1;
            }
        }

        >footer {
            @include n-row1;
            margin-top: 20px;

            >span {
                @include n-row1;
                gap: 10px;
                flex: 1;
                width: 0;
                justify-content: flex-start;

                .el-input {
                    width: 200px;
                }
            }

            >article {
                .el-button {
                    margin: 0;
                    margin-bottom: 10px;
                    width: 120px;
                    display: block;
                }
            }
        }
    }

    .pcomputed-dialog {
        >h3 {
            @include n-row1;
            justify-content: flex-end;
        }

        >ul {
            margin-top: 20px;

            >li {
                @include n-row1;
                gap: 10px;
                font-size: 14px;
                color: #555;
                border-bottom: 1px solid #eee;
                height: 40px;

                >i {
                    color: #999;
                }

                .el-button {
                    margin-left: auto;

                    &+.el-button {
                        margin-left: 0;
                    }
                }
            }
        }
    }

}
</style>

<template>
    <div class="app-container pcomputed">
        <ul class="pcomputed-list">
            <li>
                <h3>管线建设投资</h3>
                <article class="pcomputed-list-des">
                    <span>请输入</span>
                    <div>
                        <p>管线总长度(km)：<el-input v-model="params2.f" /></p>
                        <p>管道直径(m):<el-input v-model="params2.d" /></p>
                        <p>管道壁厚(m)：<el-input v-model="params2.e" /></p>
                        <p>管材价格(元/吨)：<el-input v-model="params2.d1" /></p>
                    </div>
                </article>
                <footer>
                    <span>
                        <p>管线建设投资：{{ params.e1 }} 亿元</p><br>
                    </span>
                    <el-button type="primary" plain @click="computed1">计算</el-button>
                    <el-button @click="handleClickAndClear($event, ['f', 'd', 'e', 'd1', 'e1'])">清零</el-button>
                </footer>
            </li>
            <li>
                <h3>压气站建设投资</h3>
                <article class="pcomputed-list-des">
                    <span>请输入</span>
                    <div>
                        <p>压气站数目(座)：<el-input v-model="params2.r" /></p>
                        <p>压气站建站花费(亿元/座)：<el-input v-model="params2.g1" /></p>
                    </div>
                </article>
                <footer>
                    <span>
                        <p>压气站建设投资：{{ params.h1 }} 亿元</p>
                    </span>
                    <el-button type="primary" plain @click="computed2">计算</el-button>
                    <el-button @click="handleClickAndClear($event, ['r', 'g1', 'h1'])">清零</el-button>
                </footer>
            </li>
            <li>
                <h3>流动资金、运营成本和销售收入计算</h3>
                <article class="pcomputed-list-des">
                    <span>请输入</span>
                    <div>
                        <p>管道平均压力(MPa)：<el-input v-model="params2.i1" /></p><br>
                        <p>管道平均温度(K)：<el-input v-model="params2.g" /></p><br>
                        <p>压缩因子：<el-input v-model="params2.i" /></p><br>
                        <p>管道存气单价(元/m³)：<el-input v-model="params2.l1" /></p><br>
                        <p>压气站功率(kW)：<el-input v-model="params2.m1" /></p><br>
                        <p>压缩机组效率：<el-input v-model="params2.n1" /></p><br>
                        <p>平均电价(元/kWh)：<el-input v-model="params2.o1" /></p><br>
                        <p>管输单价(元/千立方米/公里)：<el-input v-model="params2.y1" /></p><br>
                    </div>
                </article>
                <footer>
                    <span>
                        <p>流动资金：{{ params.p1 }} 亿元</p><br>
                        <p>运营成本：{{ params.q1 }} 亿元/年</p><br>
                        <p>销售收入：{{ params.z1 }} 亿元/年</p><br>
                    </span>
                    <el-button type="primary" plain @click="computed3">计算</el-button>
                    <el-button
                        @click="handleClickAndClear($event, ['i1', 'g', 'i', 'l1', 'm1', 'n1', 'o1', 'p1', 'q1' ,'y1' ,'z1'])">清零</el-button>
                </footer>
            </li>
            <li>
                <h3>净现值计算</h3>
                <article class="pcomputed-list-des">
                    <span>请输入</span>
                    <div>
                        <p>建设期(年)：<el-input v-model="params2.r1" /></p><br>
                        <p>运行期(年)：<el-input v-model="params2.s1" /></p><br>
                        <p>自有资金占比：<el-input v-model="params2.t1" /></p><br>
                        <p>利率(%)：<el-input v-model="params2.u1" /></p><br>
                        <p>贷款年限(年)：<el-input v-model="params2.v1" /></p><br>
                        <p>基准收益率(%)：<el-input v-model="params2.x1" /></p><br>
                    </div>
                </article>
                <footer>
                    <span>
                        <p>净现值：{{ params.w1 }} 亿元</p><br>
                    </span>
                    <el-button type="primary" plain @click="computed4">计算</el-button>
                    <el-button
                        @click="handleClickAndClear($event, ['r1', 's1', 't1', 'u1', 'v1', 'w1', 'x1'])">清零</el-button>
                </footer>
            </li>
        </ul>

        <div class="pcomputed-res">
            <h3>结果展示</h3>
            <ul>
                <li>管线建设投资：{{ params.e1 }} 亿元</li>
                <li>压气站建设投资：{{ params.h1 }} 亿元</li>
                <li>流动资金：{{ params.p1 }} 亿元</li>
                <li>运营成本：{{ params.q1 }} 亿元/年</li>
                <li>净现值：{{ params.w1 }} 亿元</li>
            </ul>
            <footer>
                <span>项目名：<el-input v-model="params.name" /></span>
                <article>
                    <el-button plain type="primary" @click="save">存储</el-button>
                    <el-button plain type="primary" @click="handleClickAndShow">编辑</el-button>
                </article>
            </footer>
        </div>
        <el-dialog title="项目列表" v-model="listConf.show">
            <div class="pcomputed-dialog">
                <h3><el-button type="primary" @click="add" plain>新增项目</el-button></h3>
                <ul>
                    <li v-for="item in filteredList" :key="item.id">
                        <i>{{ filteredList.indexOf(item) + 1 }}</i>
                        {{ item.name }}
                        <el-button type="primary" @click="check(item)" link>编辑</el-button>
                        <el-button type="danger" @click="del(item, idx)" link>删除</el-button>
                    </li>
                </ul>
            </div>


        </el-dialog>


    </div>
</template>
<script>



export default {
    data() {
        window.vm = this
        return {
            listConf: {
                show: true,
                list: [
                    {
                        id: null,
                        name: '',
                        f: '',   //管道总长
                        d: '',   //管道直径
                        e: '',   //管道壁厚
                        d1: '',   //管材价格
                        e1: '',   //管线建设投资
                        r: '',   //压气站数目
                        g1: '',   //压气站建站花费
                        h1: '',   //压气站建设投资
                        i1: '',   //管道平均压力
                        g: '',   //管道平均温度
                        i: '',   //压缩因子
                        l1: '',   //管道存气单价
                        m1: '',   //压气站功率
                        n1: '',   //压缩机组效率
                        o1: '',   //平均电价
                        p1: '',   //流动资金
                        q1: '',   //运营成本
                        r1: '',   //建设期
                        s1: '',   //运行期
                        t1: '',   //自有资金占比
                        u1: '',   //利率
                        v1: '',   //贷款年限
                        w1: '',   //净现值
                        x1: '',   //收益率
                        y1: '',   //管输单价
                        z1: '',   //销售收入
                    },
                ],
            },
            params: {
                id: null,
                name: '',
                f: '',   //管道总长
                d: '',   //管道直径
                e: '',   //管道壁厚
                d1: '',   //管材价格
                e1: '',   //管线建设投资
                r: '',   //压气站数目
                g1: '',   //压气站建站花费
                h1: '',   //压气站建设投资
                i1: '',   //管道平均压力
                g: '',   //管道平均温度
                i: '',   //压缩因子
                l1: '',   //管道存气单价
                m1: '',   //压气站功率
                n1: '',   //压缩机组效率
                o1: '',   //平均电价
                p1: '',   //流动资金
                q1: '',   //运营成本
                r1: '',   //建设期
                s1: '',   //运行期
                t1: '',   //自有资金占比
                u1: '',   //利率
                v1: '',   //贷款年限
                w1: '',   //净现值
                x1: '',   //基准收益率
                y1: '',   //管输单价
                z1: '',   //销售收入
            },
            params2: {
                f: '',
                d: '',
                e: '',
                d1: '',
                r: '',
                g1: '',
                i1: '',
                i: '',
                l1: '',
                m1: '',
                o1: '',
                r1: '',
                s1: '',
                t1: '',
                u1: '',
                v1: '',
                x1: '',
                y1: '',
            }
        }
    },
    created() {
        this.load();
    },
    computed: {
        filteredList() {
            const username = this.$store.state.userInfo.username;
            return this.listConf.list.filter(item => item.username === username);
        }
    },
    mounted() {

    },
    watch: {

    },
    beforeUnmount() {
        this.exitsave(); // 在组件销毁前调用save方法  
        location.reload();
    },
    methods: {
        show(event) {
            this.handleClick(event)
        },
        load() {
            this.$request.get("/computed", {
                params: {
                    id: this.id,
                    username: this.username,
                    name: this.name,
                    f: this.f,
                    d: this.d,
                    e: this.e,
                    d1: this.d1,
                    e1: this.e1,
                    r: this.r,
                    g1: this.g1,
                    h1: this.h1,
                    i1: this.i1,
                    g: this.g,
                    i: this.i,
                    l1: this.l1,
                    m1: this.m1,
                    n1: this.n1,
                    o1: this.o1,
                    p1: this.p1,
                    q1: this.q1,
                    r1: this.r1,
                    s1: this.s1,
                    t1: this.t1,
                    u1: this.u1,
                    v1: this.v1,
                    w1: this.w1,
                    x1: this.x1,
                    y1: this.y1,
                    z1: this.z1,
                }
            }).then(res => {
                this.listConf.list = res
            })
        },
        del(item, idx) {
            if (this.params.id === item.id) this.params = this.params2 = {};
            const id = item.id
            this.$request.delete("/computed/" + id).then(res => {
                if (res) {
                    this.$message.success("删除成功")
                } else {
                    this.$message.error("删除失败")
                }
            })
            location.reload();
        },
        add() {
            const newData = {
                username: this.$store.state.userInfo.username,
                name: '新的项目',
                // 其他字段可以省略，或者根据需要设置为空字符串或null  
                // 在这个例子中，我们省略了其他字段，因为它们不是必需的  
            };
            this.$request.post("/computed", newData).then(res => {
                if (res) { // 假设后端响应包含一个success字段来表示操作是否成功  
                    this.$message.success("保存成功");
                } else {
                    this.$message.error("保存失败");
                }
            }).catch(error => {
                console.error(error); // 输出错误信息到控制台，便于调试  
                this.$message.error("保存过程中发生错误");
            });
            location.reload();
        },
        check(item) {
            this.listConf.show = false;
            this.params = JSON.parse(JSON.stringify(item))
            this.params2 = JSON.parse(JSON.stringify(item))
        },
        handleClickAndShow(event) {
            this.listConf.show = true;
            this.handleClick(event);
        },
        save(event) {
            this.handleClick(event)
            if (!this.isCheck()) return;
            const { listConf: { list }, params } = this;
            const idx = list.findIndex(v => v.id === params.id);
            if (!~idx) return;
            list.splice(idx, 1, JSON.parse(JSON.stringify(params)))
			this.params.f = this.params2.f
			this.params.d = this.params2.d
			this.params.e = this.params2.e
			this.params.d1 = this.params2.d1
			this.params.r = this.params2.r
			this.params.g1 = this.params2.g1
			this.params.i1 = this.params2.i1
			this.params.i = this.params2.i
			this.params.l1 = this.params2.l1
			this.params.m1 = this.params2.m1
			this.params.o1 = this.params2.o1
			this.params.r1 = this.params2.r1
			this.params.s1 = this.params2.s1
			this.params.t1 = this.params2.t1
            this.params.u1 = this.params2.u1
			this.params.v1 = this.params2.v1
			this.params.x1 = this.params2.x1
			this.params.y1 = this.params2.y1
            this.$request.post("/computed", this.params).then(res => {
                if (res) {
                    this.$message.success("保存成功")
                } else {
                    this.$message.error("保存失败")
                }
            })
            location.reload();
        },
        exitsave() {
            if (!this.isCheck1()) return;
            const { listConf: { list }, params } = this;
            const idx = list.findIndex(v => v.id === params.id);
            if (!~idx) return;
            list.splice(idx, 1, JSON.parse(JSON.stringify(params)))
            this.params.f = this.params2.f
			this.params.d = this.params2.d
			this.params.e = this.params2.e
			this.params.d1 = this.params2.d1
			this.params.r = this.params2.r
			this.params.g1 = this.params2.g1
			this.params.i1 = this.params2.i1
			this.params.i = this.params2.i
			this.params.l1 = this.params2.l1
			this.params.m1 = this.params2.m1
			this.params.o1 = this.params2.o1
			this.params.r1 = this.params2.r1
			this.params.s1 = this.params2.s1
			this.params.t1 = this.params2.t1
            this.params.u1 = this.params2.u1
			this.params.v1 = this.params2.v1
			this.params.x1 = this.params2.x1
			this.params.y1 = this.params2.y1
            this.$request.post("/computed", this.params).then(res => {
                if (res) {
                    this.$message.success("保存成功")
                } else {
                    this.$message.error("保存失败")
                }
            })
        },
        handleClickAndClear(event, keysToClear) {
            // 先执行 handleClick 的逻辑  

            let target = event.target;
            if (target.nodeName == "I" || target.nodeName == "SPAN") {
                target = event.target.parentNode;
            }
            target.blur();

            // 然后执行 clear 的逻辑来清空参数  
            this.clear(keysToClear);

            // 可以在这里继续添加其他操作  
        },

        clear(keys) {
            keys.forEach(k => {
                this.params[k] = '';
                this.params2[k] = '';
            });
        },
        isCheck() {
            if (!this.params.id) return (this.$message.error('请选择项目'), 0)
            return true;
        },

        isCheck1() {
            if (!this.params.id) return
            return true;
        },

        isNull(v) {
            return ['', null, undefined].includes(v);
        },
        computed1(event) {
            this.handleClick(event)
            const { params2: { f, d, e, d1 }, params, isNull } = this;
            if (!this.isCheck()) return;
            if (isNull(f) || isNull(d) || isNull(e) || isNull(d1)) return this.$message.error('请完善输入')
            params.f = f;
            params.d = d;
            params.e = e;
            params.d1 = d1;
            let pipelineconstruction = (3.14 / 4 * (Math.pow(d, 2) - Math.pow(d - e, 2)) * 7850 * f * d1 * 1000 / 100000000 / 1000) * 1.2;
            params.e1 = pipelineconstruction.toFixed(3);

        },
        computed2(event) {
            this.handleClick(event)
            const { params2: { r }, params2: { g1 }, params, isNull } = this;
            if (!this.isCheck()) return;
            if (isNull(params.e1)) return this.$message.error('请完成管线建设投资的计算');
            if (isNull(r) || isNull(g1)) return this.$message.error('请完善输入');
            params.r = r;
            params.g1 = g1;
            let stationconstruction = (r * g1) * 1.15;
            params.h1 = stationconstruction.toFixed(3);
        },
        computed3(event) {
            this.handleClick(event)
            const { params2: { i1, g, i, l1, m1, n1, o1, y1 }, params, isNull } = this;
            if (!this.isCheck()) return;
            if (isNull(params.h1)) return this.$message.error('请完成压气站建设投资的计算')
            if (isNull(i1) || isNull(g) || isNull(i) || isNull(l1) || isNull(m1) || isNull(n1) || isNull(o1) || isNull(y1)) return this.$message.error('请完善输入')
            params.i1 = i1;
            params.g = g;
            params.i = i;
            params.l1 = l1;
            params.m1 = m1;
            params.n1 = n1;
            params.o1 = o1;
            params.y1 = y1;
            let volumn = 3.14 / 4 * (Math.pow(params.d - params.e, 2)) * params.f * i1 * 293.15 * 1000 / (i * g * 0.101325);
            let floweconomy = volumn * l1 * 1.5 / 100000000;
            params.p1 = floweconomy.toFixed(3);
            let elec = m1 * params.r * 365 * 0.925 * o1 / n1 / 100000000;
            let numi = Number(params.i1);
            let nume = Number(params.e1);
            let tot = elec + numi * 0.0025 + nume * 0.005;
            let moneyget = params.a * 1 * y1 / 1000 * params.f;
            params.q1 = tot.toFixed(3);
            params.z1 = moneyget.toFixed(2);
        },
        computed4() {
            const { params2: { r1, s1, t1, u1, v1, x1 }, params, isNull } = this;
            if (!this.isCheck()) return;
            if (isNull(params.p1) || isNull(params.q1) || isNull(params.z1)) return this.$message.error('请完成流动资金、运营成本和销售收入的计算')
            if (isNull(r1) || isNull(s1) || isNull(t1) || isNull(u1) || isNull(v1) || isNull(x1)) return this.$message.error('请完善输入')
            params.r1 = r1;
            params.s1 = s1;
            params.t1 = t1;
            params.u1 = u1;
            params.v1 = v1;
            params.x1 = x1;
            let numh = Number(params.h1); //压气站投资
            let nume = Number(params.e1); //管线建设投资
            let numq = Number(params.q1); //流动资金
            let nump = Number(params.p1); //运营成本

            let salesRevenue = params.z1; // 销售收入  
            let businessTaxRate = 0.03; // 营业税税率  
            let incomeTaxRate = 0.25; // 所得税税率  

            // 初始参数
            let totalInvestment = numh + nume + numq; // 总投资(亿元)
            let equity = totalInvestment * t1 / 100; // 自有资金(亿元)
            let loanAmount = totalInvestment - equity; // 贷款金额(亿元)
            let operationCost = nump; // 每年运营费用(亿元)
            let annualDiscountRate = x1 / 100; // 年折现率
            let loanMonthlyInterestRate = u1 / (100 * 12); // 贷款月利率

            // 计算等额本息还款法的每月还款额
            let loanPayments = [];
            let numberOfPayments = v1 * 12;
            let remainingBalance = loanAmount;
            for (let i = 0; i < numberOfPayments; i++) {
                let monthlyPayment = remainingBalance * (loanMonthlyInterestRate / (1 - Math.pow(1 + loanMonthlyInterestRate, -numberOfPayments)))
                    .toFixed(2);
                remainingBalance -= parseFloat(monthlyPayment);
                loanPayments.push(parseFloat(monthlyPayment));
            }

            // 初始NPV
            let npv = -totalInvestment; // 建设期投资为负数

            // 运行期每年的净现金流
            for (let i = 1; i <= s1; i++) {
                let cashFlow = 0; // 每年的现金流

                // 如果还在还款期内，需要计算当年的还款额
                if (i <= v1) {
                    let payment = loanPayments[i - 1]; // 第i年的还款额（从第1年开始计算）
                    cashFlow -= payment; // 贷款还款是现金流出
                }

                // 计算销售收入、营业税和所得税的影响  
                let businessTax = salesRevenue * businessTaxRate; // 营业税  
                let taxableIncome = salesRevenue - businessTax - (i <= v1 ? loanPayments[(i - 1) * 12 + 11] : 0) - operationCost; // 应纳税所得额（如果还在还款期内，需要减去当年的还款额）  
                let incomeTax = taxableIncome * incomeTaxRate; // 所得税  
                let netSalesRevenue = salesRevenue - businessTax - incomeTax; // 净销售收入（扣除营业税和所得税后）  

                // 更新现金流计算（加入销售收入、营业税、所得税和经营成本的影响）  
                cashFlow += netSalesRevenue - operationCost; // 净销售收入减去经营成本作为现金流入（如果还在还款期内，需要再减去当年的还款额）  
                if (i <= v1) {
                    cashFlow -= loanPayments[(i - 1) * 12]; // 当年的贷款还款额是现金流出（已经包含在上面的应纳税所得额计算中，但这里再次明确表示出来）  
                }
                npv += cashFlow / Math.pow((1 + annualDiscountRate), i); // 更新NPV计算  
            }
            params.w1 = npv.toFixed(2); // 返回保留两位小数的NPV值
        },
        handleClick(event) {
            // 点击后鼠标移开恢复按钮默认样式(如果按钮没有加icon图标的话，target.nodeName == "I"可以去掉)
            let target = event.target;
            if (target.nodeName == "I" || target.nodeName == "SPAN") {
                target = event.target.parentNode;
            }
            target.blur();
        }
    }
}
</script>
